import React, { useState, StrictMode } from 'react';

import './nineG.scss';

function Zj({ value, onSquareClick }) {
    return <button className="square" onClick={onSquareClick}>{value || '.'}</button>;
}


const App = () => {
    const [squares, setSquares] = useState(Array(9).fill(null));
    const [xIsNext, setXIsNext] = useState(true);
    function calculateWinner(squares) {
        const lines = [
            [0, 1, 2],
            [3, 4, 5],
            [6, 7, 8],
            [0, 3, 6],
            [1, 4, 7],
            [2, 5, 8],
            [0, 4, 8],
            [2, 4, 6]
        ];
        for (let i = 0; i < lines.length; i++) {
            const [a, b, c] = lines[i];
            if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
                return squares[a];
            }
        }
        return null;
    }

    function handleClick(i) {
        if (squares[i] || calculateWinner(squares)) {
            return;
        }
        const nextSquares = squares.slice();
        xIsNext ? nextSquares[i] = "X" : nextSquares[i] = "O"
        setSquares(nextSquares);
        setXIsNext(!xIsNext);
    }

    const winner = calculateWinner(squares);
    let status;
    if (winner) {
        status = "Winner: " + winner;
    } else {
        status = "Next player: " + (xIsNext ? "X" : "O");
    }
    return (
        <>
            <div className='nineG'>
                <div className="status">{status}</div>
                <div className="board-row">
                    <Zj value={squares[0]} onSquareClick={() => handleClick(0)}></Zj>
                    <Zj value={squares[1]} onSquareClick={() => handleClick(1)}></Zj>
                    <Zj value={squares[2]} onSquareClick={() => handleClick(2)}></Zj>
                </div>
                <div className="board-row">
                    <Zj value={squares[3]} onSquareClick={() => handleClick(3)}></Zj>
                    <Zj value={squares[4]} onSquareClick={() => handleClick(4)}></Zj>
                    <Zj value={squares[5]} onSquareClick={() => handleClick(5)}></Zj>
                </div>
                <div className="board-row">
                    <Zj value={squares[6]} onSquareClick={() => handleClick(6)}></Zj>
                    <Zj value={squares[7]} onSquareClick={() => handleClick(7)}></Zj>
                    <Zj value={squares[8]} onSquareClick={() => handleClick(8)}></Zj>
                </div>
                <div className="resat" onClick={() => {
                    setSquares([])
                    setXIsNext(false)
                }}>重置</div>
            </div>
        </>
    );
};
export default App;